package com.qxsx.midi.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.qxsx.midi.R;
import com.qxsx.midi.model.MusicData;

import java.util.List;

public class MusicAdapter extends BaseAdapter {

	private List<MusicData> lists;

	private Context context;

	public MusicAdapter(Context context, List<MusicData> lists) {
		this.context = context;
		this.lists = lists;

	}

	@Override
	public int getCount() {
		return lists.size();
	}

	@Override
	public Object getItem(int position) {

		return lists.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		MusicData musicData = lists.get(position);
		ViewHolder viewHolder;
		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.music_item, null);
			viewHolder.iv_img = (ImageView) convertView
					.findViewById(R.id.iv_img);
			viewHolder.tv_title = (TextView) convertView
					.findViewById(R.id.tv_title);
			viewHolder.tv_author = (TextView) convertView
					.findViewById(R.id.tv_author);
			viewHolder.tv_timer = (TextView) convertView
					.findViewById(R.id.tv_timer);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		if (musicData.getTitle() != null) {
			viewHolder.tv_title.setText(musicData.getTitle());
		}
		if (musicData.getArtist() != null) {
			viewHolder.tv_author.setText(musicData.getArtist());
		}
		viewHolder.tv_timer.setText(musicData.getDuration() + "");
		Bitmap bmp = null;
		String albumPath = musicData.getAlbumKey();
		bmp = BitmapFactory.decodeFile(albumPath);
		if (null != bmp) {
			BitmapDrawable drawable = new BitmapDrawable(
					context.getResources(), bmp);
			viewHolder.iv_img.setImageDrawable(drawable);
		} else {
			viewHolder.iv_img.setBackgroundColor(Color.GRAY);
		}
		return convertView;
	}

	static class ViewHolder {
		private ImageView iv_img;// ͷ��
		private TextView tv_title;// ����
		private TextView tv_author;// ����
		private TextView tv_timer;// ʱ��
	}
}
